package com.lib.common.base;

import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.lib.common.utils.Tips;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * Created by yangju on 2018/11/17.
 */
public abstract class BaseFragment extends Fragment {
    private View mView;
    private Unbinder mUnBinder;
    protected BaseActivity mActivity;

    protected abstract int setView();
    protected abstract void init(View view);
    protected abstract void initData(Bundle savedInstanceState);
    protected final String TAG = this.getClass().getSimpleName();

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        mActivity = (BaseActivity) activity;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (mView != null) {
            ViewGroup parent = (ViewGroup) mView.getParent();
            if (parent != null) {
                parent.removeView(mView);
            }
            mUnBinder = ButterKnife.bind(this, mView);
            return mView;
        }
        beforeSetView();

        View view = new View(mActivity);
        if(setView() != 0){
            view = inflater.inflate(setView(), container, false);
            mUnBinder = ButterKnife.bind(this, view);
        }

        if(!EventBus.getDefault().isRegistered(this)){
            EventBus.getDefault().register(this);
        }

        mView = view;
        afterSetView();
        return view;
    }

    protected void beforeSetView(){}
    protected void afterSetView(){}

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        init(view);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initData(savedInstanceState);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if(null != mUnBinder) {
            mUnBinder.unbind();
            mUnBinder = null;
        }

        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    @Subscribe
    public void onEvent(String event){

    }

    public void showToast(String msg){
        Tips.showTips(mActivity, msg);
    }

    public void showToast(int sourceId){
        Tips.showTips(mActivity, mActivity.getResources().getString(sourceId));
    }
}
